package com.lw.leetcode.arr.a;

import java.util.HashMap;
import java.util.Map;

/**
 * 1496. 判断路径是否相交
 *
 * @Author liw
 * @Date 2021/6/15 21:04
 * @Version 1.0
 */
public class IsPathCrossing {

    public static void main(String[] args){
        IsPathCrossing test = new IsPathCrossing();
        boolean nesww = test.isPathCrossing("NESWW");
        System.out.println(nesww);
    }

    public boolean isPathCrossing(String path) {
        int x = 0;
        int y = 0;
        int length = path.length();
        char[] arr = path.toCharArray();
        if (path.contains("NS") || path.contains("SN") || path.contains("WE") || path.contains("EW")) {
            return true;
        }
        Map<String, Integer> map = new HashMap<>(length << 1);
        map.put("0,0", 1);
        for (int i = 0; i < length; i++) {
            char c = arr[i];
            if (c == 'N') {
                x++;
            } else if (path.charAt(i) == 'S') {
                x--;
            } else if (path.charAt(i) == 'E') {
                y++;
            } else if (path.charAt(i) == 'W') {
                y--;
            }
            String key = x + "," + y;
            if (map.get(key) == null) {
                map.put(key, 1);
            } else {
                return true;
            }
        }
        return false;
    }
}
